package com.base.util;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

public class MyExcelUtil {


    /**
     * 导出Excel文件到磁盘
     */
    public static void exportToFile(Class clazz,List<?> dataList, HttpServletResponse response){
        // workbook
        XSSFWorkbook workbook = MyExcelExportUtil.exportWorkbook(dataList);
        OutputStream out = null;
        try {
            response.setContentType("APPLICATION/OCTET-STREAM");

            // set headers for the response
            String headerKey = "Content-Disposition";
            ExcelSheet excelSheet = (ExcelSheet)clazz.getAnnotation(ExcelSheet.class);
            String filename = excelSheet.value();
            String fileNameWithExt = filename + ".xlsx";
            String headerValue = null;

            headerValue = String.format("attachment; filename=\"%s\"", URLEncoder.encode(fileNameWithExt, "utf-8"));
            response.setHeader(headerKey, headerValue);


            out = response.getOutputStream();
            // workbook 2 FileOutputStream
            workbook.write(out);
            // flush
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            try {
                if (out!=null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 导入
     */
    public static List importFromFile(Class clazz, MultipartFile file){
        InputStream inputStream =null;
        try{
            inputStream = file.getInputStream();
            List objects = MyExcelImportUtil.importExcel(clazz, inputStream);
            return objects;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            try {
                if (inputStream!=null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
}
